import { NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { VmsScript } from '@/types/Model'
import { getUser } from '@/lib/authUtils'

export async function GET(request: Request): Promise<Response> {
  try {
    const { searchParams } = new URL(request.url)
    const copy_id = searchParams.get('copy_id')
    console.log(copy_id)
    
    if (!copy_id) {
      return NextResponse.json({ error: 'Copy ID is required' }, { status: 400 })
    }

    const scripts = await prisma.vms_script.findMany({
      where: {
        copy_id: copy_id
      },
      orderBy: {
        pxh: 'asc'
      }
    })

    return NextResponse.json(scripts)
  } catch (error) {
    console.error('Error fetching scripts:', error)
    return NextResponse.json(
      { error: 'Failed to fetch scripts' },
      { status: 500 }
    )
  }
}

export async function POST(request: Request): Promise<Response> {
  try {
    const userid = await getUser(request)
    if (!userid) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }
    await prisma.vms_user.update({
      where: { id: userid },
      data: {
        script_count: {
          increment: 1
        }
      }
    })
    const body = await request.json()
    const scriptData: VmsScript = body

    const newScript = await prisma.vms_script.create({
      data: {
        ...scriptData,
        id: crypto.randomUUID(),
        finished: scriptData.finished || false,
        user_id: userid
      }
    })

    return NextResponse.json(newScript, { status: 201 })
  } catch (error) {
    console.error('Error creating script:', error)
    return NextResponse.json(
      { error: 'Failed to create script' },
      { status: 500 }
    )
  }
}

export async function PUT(request: Request): Promise<Response> {
  try {
    const userid = await getUser(request)
    if (!userid) {
      return NextResponse.json(
        { error: '未授权或登录信息过期，请登录' },
        { status: 401 }
      )
    }
    if (userid instanceof NextResponse) {
      return userid
    }
    const body = await request.json()
    const scriptData: VmsScript = body
    
    const script = await prisma.vms_script.findUnique({
      where: { id: scriptData.id }
    })
    
    if (!script) {
      return NextResponse.json(
        { error: '未找到脚本' },
        { status: 404 }
      )
    }
    
    if (script.user_id !== userid) {
      return NextResponse.json(
        { error: '无权修改他人脚本' },
        { status: 403 }
      )
    }

    if (!scriptData.id) {
      return NextResponse.json({ error: 'Script ID is required' }, { status: 400 })
    }

    const updatedScript = await prisma.vms_script.update({
      where: { id: scriptData.id },
      data: scriptData
    })

    return NextResponse.json(updatedScript)
  } catch (error) {
    console.error('Error updating script:', error)
    return NextResponse.json(
      { error: 'Failed to update script' },
      { status: 500 }
    )
  }
}
